//
//  HelperFile.swift
//  FeastBooking
//
//  Created by Imon on 2017/7/6.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import IGListKit

extension String {
    func md5() -> String {
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deinitialize()
        
        return String(format: hash as String)
    }
}

extension NSObject: ListDiffable {
    
    public func diffIdentifier() -> NSObjectProtocol {
        return self
    }
    
    public func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
        return isEqual(object)
    }
}

public func imageFromColor(color: UIColor, viewSize: CGSize) -> UIImage{
    let rect: CGRect = CGRect(x: 0, y: 0, width: viewSize.width, height: viewSize.height)
    UIGraphicsBeginImageContext(rect.size)
    let context: CGContext = UIGraphicsGetCurrentContext()!
    context.setFillColor(color.cgColor)
    context.fill(rect)
    
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsGetCurrentContext()
    return image!
}

extension UIViewController {
    func showPromptView(message: String, confirmText: String) {
        let al = UIAlertController.init(title: nil, message: message, preferredStyle: .alert)
        let cancel = UIAlertAction.init(title: confirmText, style: .cancel, handler: nil)
        al.addAction(cancel)
        self.present(al, animated: true, completion: nil)
    }
    
    func showLoginPage() {
        let loginView = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
        loginView.showRegisterView = { [unowned self] vc in
            vc.dismiss(animated: true, completion: nil)
            self.showRegisterPage()
        }
        self.present(loginView, animated: true, completion: nil)
    }
    
    func showRegisterPage() {
        let registerNaviView = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "RegisterNavigationVC") as! UINavigationController
        let registerView = registerNaviView.topViewController as! RegisterViewController
        registerView.showLoginView = { [unowned self] vc in
            vc.dismiss(animated: true, completion: nil)
            self.showLoginPage()
        }
        self.present(registerNaviView, animated: true, completion: nil)
    }
    
    func setBackBarItem() {
        let leftBt = UIButton()
        leftBt.contentHorizontalAlignment = .left
        leftBt.setImage(UIImage(named: "back_naviBar"), for: .normal)
        leftBt.tintColor = UIColor.black
        leftBt.addTarget(self, action: #selector(backForBarItem(_:)), for: .touchUpInside)
        leftBt.sizeToFit()
        //        leftBt.imageEdgeInsets.left = -10
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftBt)
    }
    
    func backForBarItem(_ sender: UIBarButtonItem) {
        self.navigationController?.popViewController(animated: true)
    }
    
    func backForButton(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
}

extension UINavigationBar {
    
    func hideBottomHairline() {
        let navigationBarImageView = hairlineImageViewInNavigationBar(view: self)
        navigationBarImageView!.isHidden = true
    }
    
    func showBottomHairline() {
        let navigationBarImageView = hairlineImageViewInNavigationBar(view: self)
        navigationBarImageView!.isHidden = false
    }
    
    private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? {
        if view.isKind(of: UIImageView.self) && view.bounds.height <= 1.0 {
            return (view as! UIImageView)
        }
        
        let subviews = (view.subviews as [UIView])
        for subview: UIView in subviews {
            if let imageView: UIImageView = hairlineImageViewInNavigationBar(view: subview) {
                return imageView
            }
        }
        
        return nil
    }
    
}

//扩展UIImageView加载网络图片
extension UIImageView {
    func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleToFill) {
        contentMode = mode
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            // The download has finished.
            if let e = error {
                print("Error downloading cat picture: \(e)")
            } else {
                // No errors found.
                // It would be weird if we didn't have a response, so check for that too.
                if let res = response as? HTTPURLResponse {
                    print("Downloaded cat picture with response code \(res.statusCode)")
                    if let imageData = data {
                        // Finally convert that Data into an image and do what you wish with it.
                        let image = UIImage(data: imageData)
                        // Do something with your image.
                        DispatchQueue.main.async() { () -> Void in
                            self.image = image
                        }
                        
                    } else {
                        print("Couldn't get image: Image is nil")
                    }
                } else {
                    print("Couldn't get response code for some reason")
                }
            }
            
            }.resume()
        
    }
    func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        downloadedFrom(url: url, contentMode: mode)
    }
}

extension UIAlertController {
    static func showConfirmAlert(message: String, in viewController: UIViewController) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel))
        viewController.present(alert, animated: true)
    }
    
    static func showConfirmAlertFromTopViewController(message: String) {
        if let vc = UIApplication.shared.keyWindow?.rootViewController {
            showConfirmAlert(message: message, in: vc)
        }
    }
}

